package org.sk.gsync.app.synch;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.sk.gsync.app.mybatis.QueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;

public class Downloader extends Thread {

    @Autowired
    @Qualifier("docsService")
    private DocsService docsService;

    @Autowired
    private QueueService queueService;

    private String folder;

    /**
     * @param folder
     *            The folder to set.
     */
    public void setFolder(final String folder) {
        this.folder = folder;
    }

    /**
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
    }

    public void downloadFile(final String exportUrl, final String filepath)
            throws IOException, MalformedURLException, ServiceException {
        System.out.println("Exporting document from: " + exportUrl);

        MediaContent mc = new MediaContent();
        mc.setUri(exportUrl);
        MediaSource ms = docsService.getMedia(mc);

        InputStream inStream = null;
        FileOutputStream outStream = null;

        try {
            inStream = ms.getInputStream();
            outStream = new FileOutputStream(filepath);

            int c;
            while ((c = inStream.read()) != -1) {
                outStream.write(c);
            }
        } finally {
            if (inStream != null) {
                inStream.close();
            }
            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
        }
    }

}
